<?php
//db 类库
//

class Db
{
    private $_trans=false;
    private $_config=array();
    private $_dbh=null;
    public $debug=false;
    public function getInstance( $config )
    {
        static $instances = array();
        $key = serialize( $config );

        if(!isset( $instances[$key] ))
        {   
            $db = new Db($config);
            $instances[ $key ] = $db;
        }
        return $instances[ $key ];
    }

    private function __construct($config){
        $this->_config=$config;
    }

    public function getDbh($con=false){
        $dbh=$this->_dbh;
        if(!$dbh ||$con){
           extract( $this->_config );
           $ctype = isset( $ctype ) ? $ctype : false;// true is long, false is short
           $charset = isset( $charset )? $charset : 'utf8';          
           $dbh = new PDO( 'mysql:host='.$host.';dbname='.$dbname, $user, $password,
            array( PDO::ATTR_PERSISTENT => $ctype ) );
          // $dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
           $dbh->query( 'SET NAMES ' . $charset );
           $this->_dbh=$dbh;
        }

        return $dbh;
    }


    public function replace($table,$rows){        
        $sql = "replace into `$table` ";
        $keys = array_keys(reset($rows));
        $sql .= "(`".implode("`,`",$keys)."`) values ";
        foreach($rows as $row){
           $row = array_map(array($this->getDbh(),'quote'),$row);
           $sql .= "(".implode(",",$row).")," ;
        }
        $sql=substr($sql,0,-1);
        if($this->debug) echo $sql."\n";
       return $this->getDbh()->query($sql); 
    }
    public function insert($table,$rows){  
        $sql = "insert into `$table` ";
        $keys = array_keys(reset($rows));
        $sql .= "(`".implode("`,`",$keys)."`) values ";
        foreach($rows as $row){
           $row = array_map(array($this->getDbh(),'quote'),$row);
           $sql .= "(".implode(",",$row).")," ;
        }
        $sql=substr($sql,0,-1);
        if($this->debug) echo $sql."\n";
       return $this->getDbh()->query($sql); 
    }
    public function query($sql){
       return $this->getDbh()->query($sql); 
    }
    public function beginTransaction(){
        return $this->getDbh()->beginTransaction();
    }
    public function rollBack(){
       return $this->getDbh()->rollBack();
    }
    public function commit(){
       return $this->getDbh()->commit();
    }
    public function reconnect(){
        $status = $this->getDbh()->getAttribute(PDO::ATTR_SERVER_INFO);
        if(strpos($status , 'MySQL server has gone away')!==false)
        {
             $this->getDbh(true);   
        }
    }
    public function getCount($sql){
        $rst = $this->query($sql);
        return $rst->fetchColumn();
    }    
}
